#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 视图
from app import app, db
from app.models import Todo, TodoForm
from flask import render_template, request


@app.route('/')
def index():
    form = TodoForm()
    todos = Todo.query.all()
    return render_template('index.html', todos=todos, form=form)


@app.route('/add', methods=['POST'])
def add():
    form = TodoForm(request.form)
    if form.validate():
        content = request.form['content']
        todo = Todo(content=content)
        db.session.add(todo)
        db.session.commit()
        todos = Todo.query.all()
        return render_template('index.html', todos=todos, form=form)
    return render_template('index.html', form=form)


@app.route('/done/<string:todo_id>')
def done(todo_id):
    form = TodoForm()
    todo = Todo.query.filter_by(id=todo_id).first_or_404()
    todo.status = 1
    db.session.add(todo)
    db.session.commit()
    todos = Todo.query.all()
    return render_template('index.html', todos=todos, form=form)


@app.route('/undone/<int:todo_id>')
def undone(todo_id):
    form = TodoForm()
    todo = Todo.query.filter_by(id=todo_id).first_or_404()
    todo.status = 0
    db.session.add(todo)
    db.session.commit()
    todos = Todo.query.all()
    return render_template('index.html', todos=todos, form=form)


@app.route('/delete/<int:todo_id>')
def delete(todo_id):
    form = TodoForm()
    todo = Todo.query.filter_by(id=todo_id).first_or_404()
    db.session.delete(todo)
    db.session.commit()
    todos = Todo.query.all()
    return render_template('index.html', todos=todos, form=form)


@app.errorhandler(404)
def not_found(e):
    return render_template('404.html'), 404
